﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model;
using DAL;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FubiManger.UI
{
    public class Delivery
    {
        public string merchantid { get; set; }
        private ms_merchant merchant = new ms_merchant();
        private const string tokenurl = "https://api.weixin.qq.com/cgi-bin/token";
        /// <summary>
        /// 下单
        /// </summary>
        public string SetDelivery()
        {
            merchant = merchantDal.Querybyid(merchantid);
             List < ms_order > ordlist = orderDal.QueryDelivery(merchantid);
            // 按科目分组并计算每个分组的人数
            var ords = ordlist.GroupBy(s => s.consignee_address);
            List<ms_order> ordlist2 = new List<ms_order>();
            if (ords.Count() > 0)
            {
                foreach (var group in ords)
                {
                    GetDelivery(ordlist2, group, merchant);
                }
            }
           return ords.Count().ToString();
        }
        /// <summary>
        /// 配送下单
        /// </summary>
        /// <param name="ordlist"></param>
        /// <param name="group"></param>
        /// <param name="merchant"></param>
        private static void GetDelivery(List<ms_order> ordlist, IGrouping<string, ms_order> group, ms_merchant merchant)
        {
            ordlist = new List<ms_order>();
            foreach (var ms_order in group)
            {
                ms_order order = new ms_order();
                order = ms_order;
                ordlist.Add(order);
            }
            string o_ordersn = "Y" + DateTime.Now.ToString("yyyyMMddHHmmss");
            h_order ord = new h_order();
            ord.o_ordersn = o_ordersn;//订单号
            ord.o_shop_name = merchant.merchant_name;//商户名称
            ord.o_residential = ordlist[0].consignee_address;//小区
            ord.o_tel = merchant.contact_person_tel;//联系电话
            ord.o_delivery_fee = (ordlist.Count * Convert.ToDouble(merchant.distribution_costs)).ToString("f2");//配送费
            ord.o_pickup_address = merchant.address;//商家地址
            ord.o_delivery_time_start = DateTime.Now.ToString("yyyy-MM-dd" + " 11:45");//起始时间
            ord.o_delivery_time_end = DateTime.Now.ToString("yyyy-MM-dd" + " 12:45");//结束时间
            ord.o_delivery_address = ordlist[0].consignee_address;//商家地址
            ord.o_create_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//创建时间            

            h_orderDal.Addord(ord);
            foreach (var ms_order in ordlist)
            {

                List<Gdpro> gdpros = new List<Gdpro>();
                string goodinfo = "";
                JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
                gdpros = js.Deserialize<List<Gdpro>>(ms_order.goods_info);
                h_order_goods good = new h_order_goods();
                good.og_oordersn = o_ordersn;
                good.og_ordersn = ms_order.order_sn;
                good.og_delivery_fee = merchant.distribution_costs;
                for (int i = 0; i < gdpros.Count; i++)
                {
                    if (i == 0)
                        goodinfo = gdpros[i].proname + "*" + gdpros[i].count;
                    else
                        goodinfo += "+" + gdpros[i].proname + "*" + gdpros[i].count;
                }
                good.og_goodsinfo = goodinfo;//商品
                good.og_tel = ms_order.consignee_tel;//收货人电话
                good.og_nickname = ms_order.consignee_name;//收货人
                good.og_delivery_address = ms_order.consignee_address;//收货地址
                good.og_paysn = ms_order.pay_sn;//支付编号
                good.og_openid = ms_order.openid;//openid
                h_orderDal.Addgoods(good);
                orderDal.Updatestatus(ms_order.order_sn,"4");
                Send(ms_order.pay_sn, ms_order.openid);
            }

        }

        /// <summary>
        /// 发货通知
        /// </summary>
        /// <param name="out_trade_no"></param>
        /// <param name="openid"></param>
        private static void Send(string out_trade_no, string openid)
        {
            SortedDictionary<string, string> payDict = new SortedDictionary<string, string>();
            List<Shiplist> splist = new List<Shiplist>();
            Shiplist sping = new Shiplist();
            sping.item_desc = "外卖";
            splist.Add(sping);
            Openkey op = new Openkey();
            op.openid = openid;
            orderkey odk = new orderkey();
            odk.order_number_type = "1";
            odk.out_trade_no = out_trade_no;
            odk.mchid = "1645910188";
            Shipping ship = new Shipping();
            ship.order_key = odk;
            ship.delivery_mode = "1";
            ship.logistics_type = "4";
            ship.shipping_list = splist;
            ship.upload_time = "2022-12-15T13:29:35.120+08:00";
            ship.payer = op;
            string param1 = JsonConvert.SerializeObject(ship);
            //string str = param1.Replace("\\","");
            string param = "grant_type=client_credential&appid=wx5f37feb4be8e16f3&secret=070534f3f823ff12b6b6e3064ea5dded";

            string result = requestGet(tokenurl, param);
            JObject json = (JObject)JsonConvert.DeserializeObject(result);
            string token = json["access_token"].ToString();
            string url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" + token;
            requestPost(url, param1);
        }
        /*
        * HTTP的Get请求方式
        * strUrl 请求地址
        * param 请求数据
        */
        public static string requestGet(string strUrl, string param)
        {


            HttpWebRequest httpWebRequest = WebRequest.Create(strUrl + "?" + param) as HttpWebRequest;
            httpWebRequest.Method = "GET";      //指定允许数据发送的请求的一个协议方法
            httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";       //设置 ContentType 属性设置为适当的值
            WebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse;        //发起请求,得到返回对象
            Stream dataStream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            string returnStr = reader.ReadToEnd();
            // Clean up the streams and the response.
            reader.Close();
            webResponse.Close();
            return returnStr;
        }
        public static string requestPost(string strUrl, string param)
        {


            HttpWebRequest httpWebRequest = WebRequest.Create(strUrl) as HttpWebRequest;
            httpWebRequest.Method = "POST";      //指定允许数据发送的请求的一个协议方法
            httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=utf-8";       //设置 ContentType 属性设置为适当的值
            byte[] data = Encoding.UTF8.GetBytes(param);
            using (Stream stream = httpWebRequest.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);     //写入数据
            }
            WebResponse webResponse = httpWebRequest.GetResponse() as HttpWebResponse;        //发起请求,得到返回对象
            Stream dataStream = webResponse.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
            string returnStr = reader.ReadToEnd();
            // Clean up the streams and the response.
            reader.Close();
            webResponse.Close();
            return returnStr;

        }
    }
}
